package cool.taomu.toolkit.kademlia.provider

import com.google.inject.Inject
import cool.taomu.toolkit.entity.TaomuConfig
import cool.taomu.toolkit.kademlia.entity.KademliaNode
import cool.taomu.toolkit.kademlia.service.RoutingTable
import cool.taomu.toolkit.kademlia.utils.KademliaUtils
import javax.inject.Named
import javax.inject.Provider
import com.google.gson.reflect.TypeToken
import java.util.List
import cool.taomu.toolkit.rpc.thrift.entity.ThriftConfig
import java.util.WeakHashMap
import org.slf4j.LoggerFactory

class RoutingTableProvider implements Provider<RoutingTable> {
	val static LOG = LoggerFactory.getLogger(RoutingTableProvider);
	@Inject
	@Named("taomu.kademlia.name")
	String name;

	@Inject(optional=true)
	@Named("taomu.kademlia.k")
	int k = 8;
	
	@Inject(optional=true)
	@Named("taomu.rpc.server.thrift")
	TaomuConfig config;

	override get() {
		var server = config.get(new TypeToken<List<ThriftConfig>>() {})
		val cache = new WeakHashMap<String, ThriftConfig>();
		server.forEach[c|
			cache.put(c.name,c)
		]
		var info = cache.get(name);
		var localNode = new KademliaNode();
		localNode.id = KademliaUtils.createNodeId();
		localNode.host = info.host
		localNode.port = info.port
		LOG.info("生成的本地节点信息:{}",localNode)
		return new RoutingTable(localNode, k);
	}

}
